<?php
declare(strict_types=1);

/**
 * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 * @link      https://cakephp.org CakePHP(tm) Project
 * @since     0.2.9
 * @license   https://opensource.org/licenses/mit-license.php MIT License
 */
namespace App\Controller;


/**
 * Static content controller
 *
 * This controller will render views from templates/Pages/
 *
 * @link https://book.cakephp.org/4/en/controllers/pages-controller.html
 */
class ImgContentsController extends AppController
{
	public function initialize(): void
    {
        parent::initialize();
    }
    private $hostURL = 'http://127.0.0.1/cake4bg/files/';

    public function imgList() {
	    $pageSize = $this->request->getData('pageSize');
        $page = $this->request->getData('page');
        if(empty($pageSize) || !is_numeric($pageSize) || $pageSize <1 || $pageSize > 100){
            $pageSize = 30;
        }
        if(empty($page) || !is_numeric($page)){
            $page = 1;
        }

	    $where = [];
	    if(!empty($this->request->getData('title'))){
	       $where['title LIKE'] = '%' . $this->request->getData('title') . '%';
        }

        if(!empty($this->request->getData('category_id'))){
            $where['category_id'] = $this->request->getData('category_id');
        }

        if(is_numeric($this->request->getData('status'))){
            $where['status'] = $this->request->getData('status');
        }

        $result= $this->ImgContents->find()
            ->select(['id','title', 'category_id', 'status', 'add_time'])
            ->where($where)
            ->order(['id DESC'])
            ->limit($pageSize)
            ->page($page);

        $total = $result->count();
        $result = $result->toArray();

        $ImgCategories = $this->getTableLocator()->get('ImgCategories');
        $categories = $ImgCategories->find('treeList', ['spacer' => ''])->toArray();
        foreach($result as $k=>$v) {
            $result[$k]['category'] = empty($categories[$v['category_id']])? '未分类' : $categories[$v['category_id']];
            $result[$k]['add_time'] = date('Y-m-d', $v['add_time']);
        }


        $this->G->success('Success', ['list'=>$result, 'total'=> $total, 'page' => $page, 'pageSize' => $pageSize]);
    }

    public function add()
    {
        $imgContent = $this->ImgContents->newEntity($this->request->getData());
        $imgContent->add_time = time();
        if($imgContent->getErrors()){
            $this->G->error($imgContent->getErrors());
            return null;
        }
        if ($this->ImgContents->save($imgContent)){
            $this->G->success('success', $imgContent->id);
        } else {
            $this->G->error('add_error');
        }
    }

    public function update()
    {
        $id = $this->request->getData('id');
        if(!is_numeric($id)) {
            $this->G->error('id_error');
            return null;
        }
        $imgContent = $this->ImgContents->get($id);
        $imgContent = $this->ImgContents->patchEntity($imgContent, $this->request->getData());
        if($imgContent->getErrors()){
            $this->G->error($imgContent->getErrors());
        }
        if ($this->ImgContents->save($imgContent)){
            $this->G->success('success');
        } else {
            $this->G->error('update_error');
        }
    }

    public function delete()
    {

        $imgContent = $this->ImgContents->newEntity(
            $this->request->getData(),
            ['validate' => 'delete']
        );
        if ($imgContent->getErrors()){
            $this->G->error($imgContent->getErrors());
            return null;
        }
        $result = $this->ImgContents->deleteAll(['id IN' =>  $this->request->getData('ids')]);
        if($result == 0){
            $this->G->error('no_data_deleted');
            return null;
        }
        $this->G->success('success');
    }

    public function setStatus()
    {
        $imgContent = $this->ImgContents->newEntity(
            $this->request->getData(),
            ['validate' => 'update']
        );
        if ($imgContent->getErrors()){
            $this->G->error($imgContent->getErrors());
            return null;
        }

        $result = $this->ImgContents
            ->query()
            ->update()
            ->set(['status' => $this->request->getData('status')])
            ->where(['id IN' => $this->request->getData('ids')])
            ->execute();
        if(!$result){
            $this->G->error($result);
            return null;
        }
        $this->G->success('success');
    }

    public  function view()
    {
        $imgContent = $this->ImgContents->newEntity(
            $this->request->getData(),
            ['validate' => 'view']
        );
        if ($imgContent->getErrors()){
            $this->G->error($imgContent->getErrors());
            return null;
        }
        $result = $this->ImgContents->get( $this->request->getData('id'));
        if(!$result){
            $this->G->error($result);
            return null;
        }
        $result['imgHost'] = $this->hostURL;
        $this->G->success('success', $result);
    }

    public function userImgList() {
        $pageSize = $this->request->getData('pageSize');
        $page = $this->request->getData('page');
        if(empty($pageSize) || !is_numeric($pageSize) || $pageSize <1 || $pageSize > 100){
            $pageSize = 30;
        }
        if(empty($page) || !is_numeric($page)){
            $page = 1;
        }

        $where = ['status' => 1];

        if(!empty($this->request->getData('category_id'))){
            $where['category_id'] = $this->request->getData('category_id');
        }

        if(!empty($this->request->getData('title'))){
            $where['title LIKE'] = '%' . $this->request->getData('title') . '%';
        }

        $result= $this->ImgContents->find()
            ->select(['id','title', 'img'])
            ->where($where)
            ->order(['id DESC'])
            ->limit($pageSize)
            ->page($page);

        $total = $result->count();
        $result = $result->toArray();

        $this->G->success('Success', ['list'=>$result, 'total'=> $total, 'page' => $page, 'pageSize' => $pageSize, 'hostURL' => $this->hostURL]);
    }

    public  function userView()
    {
        $imgContent = $this->ImgContents->newEntity(
            $this->request->getData(),
            ['validate' => 'view']
        );
        if ($imgContent->getErrors()){
            $this->G->error($imgContent->getErrors());
            return null;
        }
        $result = $this->ImgContents->get( $this->request->getData('id'));
        if(!$result){
            $this->G->error($result);
            return null;
        }
        if($result['status'] == 0){
            $this->G->error('img_disabled');
            return null;
        }
        $result['imgHost'] = $this->hostURL;
        $this->G->success('success', $result);
    }

    //上传
    public function updateImg()
    {
        $this->loadComponent('Uploader');
        $re = $this->Uploader->upload();
        if ($re['status'] === 200) {
            $this->G->success('ok',$re['data']);
        } else {
            $this->G->error($re['msg']);
        }
    }

}
